var app = getApp()
var ConstantData = require('../../../common/constant_data.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    dataLi: [],
    showDialog: false,
    state: '',
    addressID: '',
    hospitalName: '',
    // lala:"该轮椅<span style='color:#03AC50'>EQU_NUM</span>已被预约,请租赁其他轮椅,
    renderedByNode: true,
    hospital: 31,
    btnState:true,
   
    leaseEquipList:[],
    // 预约点列表
    prePointList:[],
    prePoint:'请选择预约点',
    select:false,
    // 预约类型
    preTypeList:[],
    preType:'轮椅',
    length:4,
    cancelSubErrTip: '您今天只能预约一次哦!'
  },
  getPhoneNumber: function (e) {
    var that = this;
    console.log(e.detail.errMsg)
    console.log(e.detail.iv)
    console.log(e.detail.encryptedData)
    if (e.detail.errMsg.indexOf('user deny') != -1) {
      wx.navigateTo({
        url: '/pages/login/login',
      })
      return;
    } else {
      wx.showLoading({
        title: '登录中...',
      });
      //解密数据并登录成功
      app.executeRequest(function (header) {

        wx.request({
          url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease/auth/wxPhoneAuthLogin',
          method:'POST',
          header: header,
          data: {
            iv: encodeURIComponent(e.detail.iv),
            encryptedData: encodeURIComponent(e.detail.encryptedData)
          },
          success: function (res) {
            console.log(res.data.result,'res.data.result')
            getApp().hideLoading();
            console.log('getPhoneNumber--res', res);
            let netErr = app.handleRes(res, that);
            if (netErr) {
              wx.navigateTo({
                url: '/pages/login/login',
              })
              return
            }
            if (res.data.result === 0) {
              //登录成功
              wx.showToast({
                title: '登录成功',
              });
              var btt = that.data.phoneAuthBtt;

              wx.setStorageSync('nophone', '2');
              app.globalData.loginData.nophone = 2;
              
              that.setData({
                user_id: res.data.uid?res.data.uid:'',
                phoneAuthStatus: false,
                phoneAuthBtt:''
              })
              that.openConfirm()

              if (btt == 'scan') {
                let qrc = wx.getStorageSync('scan_qrc');
                if (qrc) {
                  console.warn('登录成功直接连接');
                  that.getDevIdAndConnect(qrc,'login');
                } else {
                  console.warn('登录成功调起摄像头');
                  that.scan();
                }
              } else if (btt == 'record_user_deposit') {
                wx.navigateTo({
                  url: '../../../pages/user_record/deposit/user_deposit',
                })
              } else if (btt == 'outpatient_add_employer') {
                //爱心租赁
                wx.navigateTo({
                  url: '../outpatient_service/manage_employer/manage_employer',
                })
              } else if (btt == 'outpatient_manage_careworker') {
                //门诊爱心租赁护工管理
                wx.navigateTo({
                  url: '../outpatient_service/manage_careworker/manage_careworker',
                })
              } else if (btt == 'deposit_record') {
                //押金记录
                wx.navigateTo({
                  url: '../../../pages/user_record/deposit/user_deposit',
                })
              } else if (btt == 'no_return_blue_timeout') {
                //押金记录
                let desc = wx.getStorageSync("alertBoxTipContent");
                that.setData({
                  alertBoxStatus: true,
                  alertBoxTipContent: desc,
                  alertBoxBtnName: "确 定"
                })
              } else if (btt == 'manager_hospitallist'){
                wx.navigateTo({
                  url: '../manager/hospitallist/hospitallist',
                })
              } else if (btt == 'opt_user_admin_menus'){
                wx.navigateTo({
                  url: '../opt_user_admin/menus/menus',
                })
              } else if (btt == 'user_phone_code'){
                wx.navigateTo({
                  url: '../help/user_phone_coce/user_phone_code',
                })
              } else { }
            } else if (res.data.result === 4) {
              wx.showToast({
                title: res.data.description,
                icon: "none"
              });
            } else {
              that.setData({
                phoneAuthStatus: true,
                phoneAuthBtt: 'scan',
                loading_show:false
              });
              wx.showToast({
                title: '请先登录',
                icon: 'none'
              })
            }
          },
          fail:function(err){
            getApp().hideLoading();
            wx.navigateTo({
              url: '/pages/login/login',
            })
          }
        });

      });
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    that.data.subType = options.type ? options.type : ''
    if(options.hospitalId){
      that.setData({
        hospital:options.hospitalId,
      })
    }
    let nophone = app.getUserLoginNoPhone();
    if (nophone == 1) {
      that.setData({
        btnState:true
      })
      console.log(that.data.btnState,"wx.getStorageSync('nophone') == 1")
    }else{
      that.setData({
        btnState:false
      })
    }
  },
  getauthList(){
    var that = this
    app.executeRequest(function (header) {
      wx.request({
        url: app.BASE_URL + '/reserve_lease/getCanReserveByTypePosition',
        // url: 'http://localhost:8088/visfull-vbzd/reserve_lease/getCanReserveByTypePosition',
        method:'POST',
        header: header,
        data: {
          hpMechanismId: that.data.hospital,
          type: that.data.subType
        },
        success: (res) => {
          console.log(res)
          if(res.data.data == null) {
             let desc = res.data.description ? res.data.description : "请重试"; 
             wx.showToast({
               title: desc,
             })
             return;
          }                
          let typeSubNumMap = res.data.data.typeSubNum;
          let typeList = res.data.data.subTypeList
          let leaseEquipList = new Array()
          for(var i=0; i<typeList.length; i++) {
              let type = typeList[i]
              leaseEquipList.push({
                content:'可预约'+type+'数量',
                number: typeSubNumMap[type]
            }) 
          }
          let subTypeList = res.data.data.subTypeList
          let preTypeList = new Array()
          for(var i=0;i<subTypeList.length;i++) {
              preTypeList.push({
                label: subTypeList[i],
                checked: false
            })
          }
          preTypeList[0].checked = true
          that.data.subPositionData = res.data.data.typeSubPosition

          
          that.setData({
              leaseEquipList: leaseEquipList,
              prePointList: res.data.data.positionList,
              preTypeList: preTypeList,
              preType: preTypeList[0].label,
              prePoint: res.data.data.positionList[0],
              dataLi: [],
              hospitalName: res.data.data.hospitalName ? res.data.data.hospitalName : "",
              length:leaseEquipList.length
          });

          let subPositionData = that.data.subPositionData
          console.log('subPositionData=======================>',subPositionData)
    
          let positionList = subPositionData[preTypeList[0].label]
          console.log('positionList=============================>',positionList[0])
          if(positionList && that.data.prePoint && that.data.prePoint != '请选择预约点') {
            let list = new Array()
            for(var i=0;i<positionList.length;i++) {
                if(positionList[i].hpPosition == that.data.prePoint) {
                    list.push(positionList[i])
                } 
            }
            positionList = list
          }
          that.setData({
            dataLi: positionList ? positionList : []
          })
          for (let i = 0; i < that.data.dataLi.length; i++) {
            if (that.data.dataLi[i].singleResverCount > 0) {
              that.setData({
                ["dataLi[" + i + "].checked"]: "true",
                addressID: that.data.dataLi[i].hpPosition
              })
              console.log(that.data.addressID, 'that.data.addressID')
              break;
            }
          }
          let nophone = app.getUserLoginNoPhone();
          if (nophone == 1) {
            that.setData({
              btnState:true
            })
            console.log(that.data.btnState,"wx.getStorageSync('nophone') == 1")
          }else{
            that.setData({
              btnState:false
            })
          }
        }
      })
    })

  },
  openConfirm: function () {
    var that = this
    app.executeRequest(function (header) {
        wx.request({
          url: app.BASE_URL + '/reserve_lease/insertReserveRecord',
        //   url: 'http://localhost:8088/visfull-vbzd/reserve_lease/insertReserveRecord',
          method:'POST',
          header: header,
          data: {
            hpMechanismId: that.data.hospital,
            hpPosition: that.data.addressID,
            type: that.data.subType,
            equCategory: that.data.preType
          },
          success: (res) => {
            console.log(res, 'wozhenshicaocaole')
            var data = res.data.data
            that.setData({
              state: data.state, //当前状态 比如 已预约，已租借使用
              subAddress: data.subAddress, //	租借地址
              equNum: data.equNum, //租借的轮椅编号
              subTime: data.subTime, //	预约时间
              pileNum: data.pileNum,
              cancelSubErrTip: res.data.description ? res.data.description : that.data.cancelSubErrTip
            })
            console.log(that.data.state, that.data.subAddress, that.data.equNum, that.data.subTime, 'data', 'data')
            if (that.data.state == '预约成功') {
              wx.navigateTo({
                url: '../subSuccess/subSuccess?state=' + that.data.state + '&subAddress=' + that.data.subAddress + '&equNum=' + that.data.equNum + '&subTime=' + that.data.subTime + '&pileNum=' + that.data.pileNum + '&eqType=' + that.data.preType,
              })
            } else {
              that.setData({
                showDialog: true
              });
            }
          }
        })
      
    })

  },
  closeConfirm: function () {
    this.setData({
      showDialog: false
    });
  },
  //下拉选择方法
  bindShowMsg() {
    this.setData({
        select: !this.data.select
    })
  },
  /**
   * 已选下拉框
   */
  mySelect(e) {
    console.log(e)
    let that = this
    var name = e.currentTarget.dataset.name
    that.setData({
        prePoint: name,
        select: false
    })
    let subPositionData = that.data.subPositionData
    console.log('subPositionData=======================>',subPositionData)
    
    let positionList = subPositionData[that.data.preType]
    console.log('positionList=============================>',positionList)
    if(positionList) {
        let list = new Array()
        for(var i=0;i<positionList.length;i++) {
            if(positionList[i].hpPosition == name) {
                list.push(positionList[i])
            } 
        }
        positionList = list
    }
    that.setData({
        dataLi: positionList ? positionList : []
    })
    for (let i = 0; i < that.data.dataLi.length; i++) {
        if (that.data.dataLi[i].singleResverCount > 0) {
            that.setData({
                ["dataLi[" + i + "].checked"]: "true",
                addressID: that.data.dataLi[i].hpPosition
            })
            console.log(that.data.addressID, 'that.data.addressID')
            break;
        }
    }
  }, 
  // 预约类型单选切换
  typeChange(e) {
    let that = this
    that.setData({
        preType:e.detail.value
    })
    let subPositionData = that.data.subPositionData
    let positionList = subPositionData[that.data.preType]
    if(positionList && that.data.prePoint && that.data.prePoint != '请选择预约点') {
        let list = new Array()
        for(var i=0;i<positionList.length;i++) {
            if(positionList[i].hpPosition == that.data.prePoint) {
                list.push(positionList[i])
            } 
        }
        positionList = list
    }
    
    that.setData({
        dataLi: positionList ? positionList : []
    })
    for (let i = 0; i < that.data.dataLi.length; i++) {
        if (that.data.dataLi[i].singleResverCount > 0) {
          that.setData({
            ["dataLi[" + i + "].checked"]: "true",
            addressID: that.data.dataLi[i].hpPosition
          })
          console.log(that.data.addressID, 'that.data.addressID')
          break;
        }
      }
  },
  // 选中radio值
  radioChange(e) {
    var that = this
    that.setData({
      addressID: e.detail.value
    })
    console.log('radio发生change事件，携带value值为：', e)
  },
  // 前往租赁详情 
  gotoZulin() {
    wx.navigateTo({
      url: '../../../pages/user_record/lease/user_lease',
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this
    that.getauthList()

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})